//################################## 初始化 ######################################
var layers = [];													// 声明层
var player;															// 用户角色
var scene;															// 用户场景
var camera = new PIXI.Container();									// 创建镜头
//################################ 构造渲染器 #####################################
const app = new PIXI.Application({ background: '#1099bb', resizeTo: window });

app.ticker.add((delta) => 
{ 	
	L2D.Keys.update();
	if(player) {
		camera.position.set(app.renderer.screen.width/2, app.renderer.screen.height/2);
		camera.pivot.set(Math.floor(player.x), Math.ceil(player.y));
	}
	if(scene) scene.update();
	L2D.UIManager.update();
});
document.body.appendChild(app.view);

window.addEventListener("onorientationchange" in window ? "orientationchange" : "resize", function() {
	resize(800, 600);
});

function resize(width, height) {
	const screenRect = app.view.getBoundingClientRect();
	app.renderer.resize(screenRect.width, screenRect.height);
	
	let offsetWidth = 0;
	let offsetHeight = 0;
	if (window.orientation === 90 || window.orientation === -90) {
	  offsetWidth = screenRect.height;
	  offsetHeight = screenRect.width;
	} else {
	  offsetWidth = screenRect.width;
	  offsetHeight = screenRect.height;
	}
	
	const aspectRatio = offsetHeight / offsetWidth;
	
	// fixWidth, orientation="portrait"
	const newWidth = offsetWidth;
	const scale = newWidth / width;
	const newHeight = height * scale;
	
	camera.scale.x = newWidth / width;
	camera.scale.y = newHeight / height;
	L2D.UIManager.scale = camera.scale;
	
	//if (window.orientation === 180 || window.orientation === -180 ||
	//	window.orientation === 90 || window.orientation === -90) {
	if(false) {
	  camera.rotation = -Math.PI / 2;
	  camera.y = newWidth;
	} else {
	  camera.rotation = 0;
	  camera.y = 0;
	}
	
	L2D.UIManager.realScreen = camera.realScreen = {
	  realWidth: offsetWidth,
	  realHeight: offsetHeight,
	  width,
	  height,
	  top: 0,
	  bottom: offsetHeight / scale,
	  left: 0,
	  right: width,
	  aspectRatio
	};
	camera.realScreen.width = camera.realScreen.right - camera.realScreen.left;
	camera.realScreen.height = camera.realScreen.bottom - camera.realScreen.top;
}

//################################ 读取启动配置 ####################################
L2D.Loader.load("res/startup.json", null, function(json) {
	player = L2D.Loader.load(json.content.character);				// 新建主角 
	player.x = json.content.location.x;								// 为主角设置坐标
	player.y = json.content.location.y;	
	
	scene = L2D.Loader.load(json.content.scene, null, function() {
		global.bag.add("res/道具.item", 2);
		global.bag.test();
	});																// 新建地图
	scene.player = player; 											// 设置地图主角
	
	scene.addChild(player);											// 将角色加入地图中
	camera.addChild(scene);											// 将地图加入层中
	app.stage.addChild(camera);										// 将镜头加入场景中
	
	app.stage.addChild(L2D.UIManager);								// 将UI层加入场景中
	app.stage.addChild(L2D.UserInterface);							// 添加用户接口到场景中
	
	resize(640, 360);
});

//############################### 配置用户输入事件 ##################################
// 主角移动
function fixVelocity(x, y) {
	const maxSpeed=1.7;
	const speedStep=30;	

	var fixedY = y * player.speed/speedStep;
	player.body.velocity.y += fixedY;
	if(fixedY < 0) {
		if(player.body.velocity.y < -player.speed*maxSpeed)
			player.body.velocity.y = -player.speed*maxSpeed;
	}
	else if(fixedY > 0) {
		if(player.body.velocity.y > player.speed*maxSpeed)
			player.body.velocity.y = player.speed*maxSpeed;
	}
	
	var fixedX = x * player.speed/speedStep;
	player.body.velocity.x += fixedX;
	if(fixedX < 0) {
		if(player.body.velocity.x < -player.speed*maxSpeed)
			player.body.velocity.x = -player.speed*maxSpeed;
	}
	else if(fixedX > 0) {
		if(player.body.velocity.x > player.speed*maxSpeed)
			player.body.velocity.x = player.speed*maxSpeed;
	}
	
	Matter.Body.setVelocity(player.body, player.body.velocity);
}

L2D.Keys.bind(['up','left','down','right'], function(e) {

	// 如果打开了UI则进行UI操作
	if(L2D.UIManager.children.length > 0) {
		L2D.UIManager.keyDown(e.pressedKeys[0]);
		return;
	}

	// 受伤时不可移动
	if (player.action && player.action.constructor.name=="Hurt")
		return;

	var xspeed = 0;
	var yspeed = 0;
	for(var i = 0; i < e.pressedKeys.length; i++) {
		switch (e.pressedKeys[i]) {
			case 'up': yspeed=-1/e.pressedKeys.length; break;
			case 'left': xspeed=-1/e.pressedKeys.length; break;
			case 'down': yspeed=1/e.pressedKeys.length; break;
			case 'right': xspeed=1/e.pressedKeys.length; break;
		}
	}

	if(player.state == `attack`) {
		fixVelocity(xspeed*0.2, yspeed*0.2);
	}
	else if(scene.battle) {
		var single = player.state == "hit" ?
			0.1 : 1;

		fixVelocity(xspeed*single, yspeed*single);
	}
	else {
		player.moveTo({ x:player.x+xspeed, y:player.y+yspeed });
	}
});

L2D.Keys.bind('z', function(e) {
	// 防止重复交互
	e.preventRepeat();

	// 如果打开了UI则进行UI操作
	if(L2D.UIManager.children.length > 0) {
		L2D.UIManager.keyDown(e.pressedKeys[0]);
		return;
	}
	
	// 如果在战场内则是攻击
	if(player.scene.battle) {
		if(player.state != `attack` && (!player.action || player.action.constructor.name!="Hurt")) {
			player.attack(function(sender) {
				player.state = `idea`;
			});
		}
	} else if(scene.talker && L2D.UIManager.children.length == 0) {
		// 否则与场景交互
		player.talkTo(scene.talker);
	}

});

L2D.Keys.bind("x", function(e) {
	// 如果打开了UI则进行UI操作
	if(L2D.UIManager.children.length > 0) {
		L2D.UIManager.keyDown(e.pressedKeys[0]);
		return;
	}

	// 如果在战场内则释放技能

});

L2D.Keys.bind("a", function(e) {
	// 如果打开了UI则进行UI操作
	if(L2D.UIManager.children.length > 0) {
		L2D.UIManager.keyDown(e.pressedKeys[0]);
		return;
	}
})

L2D.Keys.bind("s", function(e) {
	// 如果打开了UI则进行UI操作
	if(L2D.UIManager.children.length > 0) {
		L2D.UIManager.keyDown(e.pressedKeys[0]);
		return;
	}
})